package com.android.publicModule.tools;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.http.ParseException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.publicModule.system.SystemInfo;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.Signature;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.util.Base64;
import android.util.Log;

public class Tools {
	
	private static boolean showLog=true;//是否打印LOG信息，默认关闭
	private static boolean saveLog=true;//是否保存LOG信息，默认关闭
	private static int showType=5;//打印LOG信息的级别，默认Log.v  (1:Log.v;2:Log.d;3:Log.i;4:Log.w;5:Log.e;6:Log.wtf)
	public static final String sdcardPath = Environment.getExternalStorageDirectory().getAbsolutePath();
	public static final String saveLogFileName = "yyAssistantSmartChat-Log.txt";//日志默认存储文件名
    private static String saveLogPath = sdcardPath+"/"+saveLogFileName;//日志默认存储路径
    private static FileWriter fWriter = null;
    public static final String TAG="YY";
    /**
     * 开启或关闭打印LOG信息
     * @param bool
     */
    public static void setShowLog(boolean bool) {
    	showLog=bool;
    }
    
    /**
     * 开启或关闭保存LOG信息
     * @param bool
     */
    public static void setSaveLog(boolean bool) {
    	saveLog = bool;
    }
    
    public static void setShowType(int type) {
    	showType = type;
    }
    
    /**
     * 打印LOG信息
     * @param tag
     * @param msg
     */
    public static void showLog(String tag, String msg) {
        if (showLog) {
        	switch(showType) {
        		case 1:
        			Log.v(tag, msg);
        			break;
        		case 5:
        			Log.e(tag, msg);
        			break;
        		case 3:
        			Log.i(tag, msg);
        			break;
        		case 2:
        			Log.d(tag, msg);
        			break;
        		case 4:
        			Log.w(tag, msg);
        			break;
        		case 6:
        			Log.wtf(tag, msg);
        			break;
        		default:
        			break;
        	}
        }
    }
    
    /**
     * 保存LOG信息
     * @param tag
     * @param msg
     */
    public static void saveLog(String tag, String msg) {
    	if (saveLog) {
        	try {
	        	if (fWriter == null) {
	        		fWriter = new FileWriter(saveLogPath, true);
	        	}
	            if(tag!=null&&msg!=null)
	            {
	            	tag+=":";
	            	if(msg.length()>=100)
	            	{
	            		tag+="\r\n";
	            	}
					fWriter.write(tag+msg+"\r\n");
					fWriter.flush();
	            }
        	} catch (IOException e) {
			} catch (Exception e) {
			}
        }
    }
    
    /**
     * 设置LOG保存路径
     * @param path
     */
    public static void setSaveLogPath(String path) {
    	saveLogPath = path;
    	fWriter = null;
    }

    /**
     * 打印并保存LOG信息
     * @param tag
     * @param msg
     */
    public static void showSaveLog(String tag, String msg) {
    	showLog(tag,msg);
    	saveLog(tag,"["+getCurrentDate("yyyy-MM-dd HH:mm:ss",null)+"]"+msg);
    }

    /**
     * 关闭写LOG文件
     */
    public static void closeSaveLog() {
    	try {
    		if (fWriter != null) {
    			fWriter.close();
    			fWriter = null;
        	}
    	} catch (IOException e) {
		} catch (Exception e) {
		}
    }
    
    /**
     * 按指定的时间和格式输出时间信息
     * @param format
     * @param date
     * @return
     */
    public static String getCurrentDate(String format,Date date) {
    	if(format==null)
    	{
    		format="yyyy-MM-dd";
    	}
    	if(date==null)
    	{
    		date=new Date();
    	}
    	String dateStr = null;
    	try {
    		SimpleDateFormat formatter = new SimpleDateFormat(format);
    		dateStr = formatter.format(date);
    	} catch (NullPointerException e) {
		} catch (IllegalArgumentException e) {
		}
		return dateStr;
    }
    
    /**
     * 按指定的时间和格式构建对应的Date实例
     * @param format
     * @param dateStr
     * @return
     */
    public static Date createFormatDate(String format,String dateStr) {
    	Date date=null;
    	if(format==null)
    	{
    		format="yyyy-MM-dd";
    	}
    	try {
    		SimpleDateFormat formatter = new SimpleDateFormat(format);
			date = formatter.parse(dateStr);
		} catch (java.text.ParseException e) {
		} catch (NullPointerException e) {
		} catch (IllegalArgumentException e) {
		}
		return date;
    }
    
    /**
     * 获取安装包信息
     * @param context
     * @return
     */
    public static ApplicationInfo getApplicationInfo(Context context,String packageName) {
    	ApplicationInfo info = null;
    	if (packageName!=null&&packageName.length()>0)
        {
	    	try {
	    		info = context.getPackageManager().getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
			} catch (NameNotFoundException e) {
				
			}
        }
    	return info;
    }
    
    /**
     * 获取安装包信息
     * @param context
     * @return
     */
    public static ApplicationInfo getApplicationInfo(Context context,String packageName,int flags) {
    	ApplicationInfo info = null;
    	if (packageName!=null&&packageName.length()>0)
        {
	    	try {
	    		info = context.getPackageManager().getApplicationInfo(packageName, flags);
			} catch (NameNotFoundException e) {
				
			}
        }
    	return info;
    }
    
    /**
     * 根据包名获取应用的安装信息
     * @param packageName
     * @return
     */
    public static PackageInfo getPackageInfo(Context context,String packageName) {
        return getPackageInfo(context,packageName,PackageManager.GET_UNINSTALLED_PACKAGES);
    }
    
    /**
     * 根据包名获取应用的安装信息
     * @param packageName
     * @return
     */
    public static PackageInfo getPackageInfo(Context context,String packageName,int flag) {
    	PackageInfo info = null;
        if (packageName!=null&&packageName.length()>0)
        {
	        try {
	            info = context.getPackageManager().getPackageInfo(packageName,flag);//PackageManager.GET_UNINSTALLED_PACKAGES
	        } catch (NameNotFoundException e) {
	           
	        }
        }
        return info;
    }
    
    /**
     * 获取安装包的包名信息等
     * @param context
     * @param path
     * @return
     */
    public static PackageInfo getPackageInfoFromPath(Context context,String path) {    
        PackageManager pm = context.getPackageManager();
        return pm.getPackageArchiveInfo(path, PackageManager.GET_UNINSTALLED_PACKAGES);//PackageManager.GET_ACTIVITIES
    }
    
	/**
	 * 获取应用签名
	 * @param info
	 * @return
	 */
	public static String getPackageSignature(PackageInfo info) {
		String platform_x509_pem = null;
		if(info!=null) {
			Signature []signatures=info.signatures;
			if(signatures!=null&&signatures.length>0)
			{
				byte []signByteArray = signatures[0].toByteArray();
				platform_x509_pem = Base64.encodeToString(signByteArray,Base64.NO_WRAP);
			}
		}
		return platform_x509_pem;
	}
	
	/**
	 * 判断应用是否为系统签名的应用
	 * @param info
	 * @return
	 */
	public static boolean getIsSystemSignature(Context context,PackageInfo info) {
		boolean isSystemSignature = false;
		if(info!=null)
		{
			String sharedUserId = info.sharedUserId;
			Tools.showLog("muge", "getIsSystemSignature() packageName="+info.packageName+" sharedUserId="+info.sharedUserId);
			if(sharedUserId!=null&&sharedUserId.equals("android.uid.system"))
			{
				isSystemSignature = true;
			}
			else
			{
				String channelInfoSignature = getPackageSignature(info);
				String systemSignature = null;
				PackageInfo systemInfo = Tools.getPackageInfo(context, "android",PackageManager.GET_SIGNATURES);
				if(systemInfo!=null)
				{
					systemSignature = getPackageSignature(systemInfo);
				}
				else
				{
					systemInfo = getPackageInfo(context, "com.android.settings",PackageManager.GET_SIGNATURES);
					if(systemInfo!=null)
					{
						systemSignature = getPackageSignature(systemInfo);
					}
				}
				if(channelInfoSignature!=null&&systemSignature!=null&&channelInfoSignature.equals(systemSignature))
				{
					Tools.showLog("muge", "getIsSystemSignature() channelInfoSignature=systemSignature");
					isSystemSignature = true;
				}
				else
				{
					Tools.showLog("muge", "getIsSystemSignature() channelInfoSignature!=systemSignature");
				}
			}
		}
		return isSystemSignature;
	}
	
	/**
	 * 判断应用是否为系统签名或内置在系统区的应用
	 * @param info
	 * @return
	 */
	public static boolean checkSystemSignatureOrSystemImg(Context context,PackageInfo info) {
		boolean isSystemSignature = false;
		if(info!=null)
		{
			isSystemSignature = getIsSystemSignature(context,info);//是否系统签名
			if(!isSystemSignature)
			{
				int installType = SystemInfo.getInstallType(context,info.packageName);
				isSystemSignature = (installType==SystemInfo.INSTALL_TYPE_SYSTEM);//是否系统区
				Tools.showLog("muge", "checkSystemSignature() packageName="+info.packageName+" installType="+installType+" isSystemSignature="+isSystemSignature);
			}
			else
			{
				Tools.showLog("muge", "checkSystemSignature() channelInfoSignature=systemSignature");
			}
		}
		return isSystemSignature;
	}
    
    /**
     * 查看SD卡剩余空间大小
     * @return
     */
    public static long getSDCardAvailableSize() {
        StatFs statFs = new StatFs(sdcardPath);
        long sdcardAvailableSize = (statFs.getBlockSize() * (long)statFs.getAvailableBlocks());
        return sdcardAvailableSize;
    }
    
    /**
     * 查看SD卡总空间大小
     * @return
     */
    public static long getSDCardTotalSize() {
        StatFs statFs = new StatFs(sdcardPath);
        long sdcardTotalSize = (statFs.getBlockSize() * (long)statFs.getBlockCount());
        return sdcardTotalSize;
    }
    
    /**
     * 查看手机剩余空间大小
     * @return
     */
    public static long getPhoneAvailableSize(Context context) {
    	long phoneAvailableSize = 0;
    	if(context!=null)
    	{
    		StatFs statFs = new StatFs(context.getFilesDir().getAbsolutePath());
    		phoneAvailableSize = (statFs.getBlockSize() * (long)statFs.getAvailableBlocks());
    	}
        return phoneAvailableSize;
    }
    
    /**
     * 查看手机总空间大小
     * @return
     */
    public static long getPhoneTotalSize(Context context) {
    	long phoneTotalSize = 0;
    	if(context!=null)
    	{
    		StatFs statFs = new StatFs(context.getFilesDir().getAbsolutePath());
    		phoneTotalSize = (statFs.getBlockSize() * (long)statFs.getBlockCount());
    	}
        return phoneTotalSize;
    }
    
    /**
     * 查看指定目录剩余空间大小
     * @return
     */
    public static long getDirAvailableSize(String path) {
        File file = new File(path);
        StatFs statFs = new StatFs(file.getAbsolutePath());
        long availableSpare = (statFs.getBlockSize() * (long)statFs.getAvailableBlocks());
        return availableSpare;
    }
    
    /**
     * 查看手机总空间大小
     * @return
     */
    public static long getDirTotalSize(String path) {
    	long dirTotalSize = 0;
    	StatFs statFs = new StatFs(path);
    	dirTotalSize = (statFs.getBlockSize() * (long)statFs.getBlockCount());
        return dirTotalSize;
    }
    
    /**
     * 智能单位换算
     * @param data//数据源
     * @param k//基数
     * @param dec//保留小数位数
     * @param unit//单位
     * @return
     */
    public static String getUnit(long data,int k,int dec,String []unit) {
    	if(unit!=null&&unit.length>0&&k>0)
    	{
    		double d = data;
    		for(int i=0;i<unit.length;i++) {
    			if(d<k)
    			{
    				if((d-(long)(d))<Math.pow(0.1, dec))
    	    		{
    	    			dec = 0;
    	    		}
    				return String.format("%."+dec+"f", d)+unit[i];
    			}
    			d/=k;
    		}
    		if((d-(long)(d))<Math.pow(0.1, dec))
    		{
    			dec = 0;
    		}
    		return String.format("%."+dec+"f", d)+unit[unit.length-1];
    	}
    	return null;
    }
    
	/**
	 * 根据Intent过滤Activity列表
	 * @param context
	 * @param intent
	 * @return
	 */
	public static List<ResolveInfo> queryIntentActivities(Context context,Intent intent) {
		if(context!=null&&intent!=null)
		{
	        return context.getPackageManager().queryIntentActivities(intent, PackageManager.GET_ACTIVITIES); 
		}
		return null;
	}
    
	public static final String browsers = ",com.android.browser,com.uc.browser,com.opera.mini.android,com.tencent.mtt,com.baidu.browser.apps,com.qihoo.androidbrowser";
	/**
	 * 使用浏览器打开指定网址
	 * @param context
	 * @param url
	 */
	public static void openURL(Context context,String url) {
		showLog("ZSZ-Tools","openBrowser() url="+url);
		if(context!=null&&url!=null&&url.length()>0)
		{
			Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			List<ResolveInfo> list = queryIntentActivities(context,intent);
			if(list!=null)
			{
				int len = list.size();
				if(len>0)
				{
					String packageName;
					ResolveInfo info;
					boolean set = false;
					for(int i=0;i<len;i++)
					{
						info = list.get(i);
						if(info!=null)
						{
							packageName = info.activityInfo.packageName;
							if(browsers.indexOf(','+packageName)>=0)
							{
								set = true;
								intent.setClassName(packageName, info.activityInfo.name);
								break;
							}
						}
					}
					if(!set)
					{
						info = list.get(0);
						intent.setClassName(info.activityInfo.packageName, info.activityInfo.name);
					}
				}
			}
			context.startActivity(intent);
		}
	}
	
	/**
	 * 求字符串的子串高效方法
	 * @param source
	 * @param start
	 * @param startInc
	 * @param end
	 * @param endInc
	 * @return
	 */
    public static String subString(String source,String start,Integer startInc,String end,Integer endInc) {
    	String result=null;
    	if(source==null||start==null||end==null)
    	{
    		return result;
    	}
    	if(startInc==null)
    	{
    		startInc=start.length();
    	}
    	if(endInc==null)
    	{
    		endInc=end.length();
    	}
		int index1=source.indexOf(start);
		int index2=0;
		if(index1>=0)
		{
			index1 += startInc;
			index2=source.indexOf(end,index1);
			index2 += endInc;
			int length = source.length();
			if(index1>=0&&index2<=length&&index2>index1)
			{
				result=source.substring(index1, index2);
			}
			else if(index1==index2)
			{
				result="";
			}
		}
		return result;
    }
	
    /**
     * 求URL的主机地址
     * @param url
     * @return
     */
	public static String getXHost(String url) {
		String xHost = null ;
		if(url.toLowerCase().startsWith("http://"))
	    {
	    	url = "http://"+url.substring(7);
	    	xHost=subString(url,"http://",null,"/",0);
	    	if(xHost==null)
	    	{
	    		xHost=subString(url,"http://",0,"?",0);
	    		if(xHost==null)
	        	{
	    			xHost=url.substring(7);
	        	}
	    	}
	    }
	    else if(url.toLowerCase().startsWith("www."))
	    {
	    	url = "www."+url.substring(4);
	    	xHost=subString(url,"www.",0,"/",0);
	    	if(xHost==null)
	    	{
	    		xHost=subString(url,"www.",0,"?",0);
	    		if(xHost==null)
	        	{
	    			xHost=url.substring(4);
	        	}
	    	}
	    }
		return  xHost;
	}
	
    /**
     * 获取字符串的hash值
     * @param str
     * @return
     */
    public static int getStringHashValue(String str) {
    	int hashCode = 0;
        if (str!=null&&str.length()>0)
        {
        	hashCode = str.hashCode();
        } 
        return hashCode;
    }
    
	/**
	 * 判断目录是否存在且可读写
	 * @param dir
	 * @return
	 */
	public static boolean isFileExistsAndCanReadWrite(File dir) {
		return dir!=null&&dir.exists()&&dir.canRead()&&dir.canWrite();
	}
	
	/**
	 * 判断剩余空间在minSize之上的SD卡是否存在
	 * @param minSize
	 * @return
	 */
	private static final String sdcardDirArr[] = {"/sdcard","/sdcard0","/sdcard1","/sdcard2"};
	public static String getSdcardPath(long minSize) {
		String path = null;
		File dir = Environment.getExternalStorageDirectory();
		if(isFileExistsAndCanReadWrite(dir)&&(minSize<=0||getDirAvailableSize(dir.getAbsolutePath())>minSize))
		{
			path = dir.getAbsolutePath();
		}
		else
		{
			if(sdcardDirArr!=null&&sdcardDirArr.length>0)
			{
				for(int i=0;i<sdcardDirArr.length;i++)
				{
					dir = new File(sdcardDirArr[i]);
					if(isFileExistsAndCanReadWrite(dir)&&(minSize<=0||getDirAvailableSize(dir.getAbsolutePath())>minSize))
					{
						path = dir.getAbsolutePath();
						break;
					}
				}
			}
		}
		return path;
	}
	
	public static boolean isPhoneFileExists(Context context,String path) {
		boolean result = false;
		if(path!=null&&path.length()>0)
		{
			if(path.startsWith("/data/data/"))
			{
				result = new File(path).exists();
			}
			else if(!path.startsWith("/"))
			{
				result = new File("/data/data/"+SystemInfo.getPackageName(context)+"/"+path).exists();
			}
			else
			{
				result = new File(path).exists();
			}
		}
		return result;
	}
	
	public static boolean isSdcardFileExists(Context context,String path) {
		boolean result = false;
		if(path!=null&&path.length()>0)
		{
			if(path.startsWith("/"))
			{
				result = new File(path).exists();
			}
			else
			{
				result = new File(sdcardPath+"/"+path).exists();
				if(!result)
				{
					if(sdcardDirArr!=null&&sdcardDirArr.length>0)
					{
						for(int i=0;i<sdcardDirArr.length;i++)
						{
							result = new File(sdcardDirArr[i]+"/"+path).exists();
							if(result)
							{
								break;
							}
						}
					}
				}
			}
		}
		return result;
	}
	
	public static boolean isFileExists(Context context,String path) {
		boolean result = false;
		if(path!=null&&path.length()>0)
		{
			if(path.startsWith("/data/data/"))
			{
				result = isPhoneFileExists(context,path);
			}
			else if(!path.startsWith("/"))
			{
				result = isSdcardFileExists(context,path);
				if(!result)
				{
					result = isPhoneFileExists(context,path);
				}
			}
			else
			{
				result = isSdcardFileExists(context,path);
			}
		}
		return result;
	}
	
	public static String getExistsPhoneFilePath(Context context,String path) {
		String filePath = null;
		if(path!=null&&path.length()>0)
		{
			File f;
			if(path.startsWith("/data/data/"))
			{
				f = new File(path);
				if(f.exists())
				{
					filePath = f.getAbsolutePath();
				}
			}
			else if(!path.startsWith("/"))
			{
				f = new File("/data/data/"+SystemInfo.getPackageName(context)+"/"+path);
				if(f.exists())
				{
					filePath = f.getAbsolutePath();
				}
			}
			else
			{
				f = new File(path);
				if(f.exists())
				{
					filePath = f.getAbsolutePath();
				}
			}
		}
		return filePath;
	}
	
	public static String getExistsSdcardFilePath(Context context,String path) {
		String filePath = null;
		if(path!=null&&path.length()>0)
		{
			File f;
			if(path.startsWith("/"))
			{
				f = new File(path);
				if(f.exists())
				{
					filePath = f.getAbsolutePath();
				}
			}
			else
			{
				f = new File(sdcardPath+"/"+path);
				if(f.exists())
				{
					filePath = f.getAbsolutePath();
				}
				else
				{
					if(sdcardDirArr!=null&&sdcardDirArr.length>0)
					{
						for(int i=0;i<sdcardDirArr.length;i++)
						{
							f = new File(sdcardDirArr[i]+"/"+path);
							if(f.exists())
							{
								filePath = f.getAbsolutePath();
								break;
							}
						}
					}
				}
			}
		}
		return filePath;
	}
	
	public static String getExistsFilePath(Context context,String path) {
		String filePath = null;
		if(path!=null&&path.length()>0)
		{
			if(path.startsWith("/data/data/"))
			{
				filePath = getExistsPhoneFilePath(context,path);
			}
			else if(!path.startsWith("/"))
			{
				filePath = getExistsSdcardFilePath(context,path);
				if(filePath!=null&&filePath.length()>0)
				{
					filePath = getExistsPhoneFilePath(context,path);
				}
			}
			else
			{
				filePath = getExistsSdcardFilePath(context,path);
			}
		}
		return filePath;
	}
	
	public static String createPhoneDir(Context context,String path) {
		String filePath = null;
		if(path!=null&&path.length()>0)
		{
			File f = null;
			if(path.startsWith("/data/data/"))
			{
				f = new File(path);
			}
			else if(!path.startsWith("/"))
			{
				f = new File("/data/data/"+SystemInfo.getPackageName(context)+"/"+path);
			}
			else
			{
				f = new File(path);
			}
			if(f!=null&&!f.exists())
			{
				f.mkdirs();
			}
			if(f!=null&&f.exists())
			{
				filePath = f.getAbsolutePath();
			}
		}
		return filePath;
	}
	
	public static String createSdcardDir(Context context,String path) {
		String filePath = null;
		if(path!=null&&path.length()>0)
		{
			File f;
			if(path.startsWith("/"))
			{
				f = new File(path);
				if(!f.exists())
				{
					f.mkdirs();
				}
				if(f!=null&&f.exists())
				{
					filePath = f.getAbsolutePath();
				}
			}
			else
			{
				f = new File(sdcardPath+"/"+path);
				if(!f.exists())
				{
					f.mkdirs();
				}
				if(f!=null&&f.exists())
				{
					filePath = f.getAbsolutePath();
				}
				else
				{
					if(sdcardDirArr!=null&&sdcardDirArr.length>0)
					{
						for(int i=0;i<sdcardDirArr.length;i++)
						{
							f = new File(sdcardDirArr[i]+"/"+path);
							if(!f.exists())
							{
								f.mkdirs();
							}
							if(f!=null&&f.exists())
							{
								filePath = f.getAbsolutePath();
								break;
							}
						}
					}
				}
			}
		}
		return filePath;
	}
	
	public static String createDir(Context context,String path) {
		String filePath = null;
		if(path!=null&&path.length()>0)
		{
			if(path.startsWith("/data/data/"))
			{
				filePath = createPhoneDir(context,path);
			}
			else if(!path.startsWith("/"))
			{
				filePath = createSdcardDir(context,path);
				if(filePath!=null&&filePath.length()>0)
				{
					filePath = createPhoneDir(context,path);
				}
			}
			else
			{
				filePath = createSdcardDir(context,path);
			}
		}
		return filePath;
	}
	
	
	public static String createPhoneEmptyFile(Context context,String path) {
		String filePath = null;
		if(path!=null&&path.length()>0)
		{
			File f = null;
			if(path.startsWith("/data/data/"))
			{
				f = new File(path);
			}
			else if(!path.startsWith("/"))
			{
				f = new File("/data/data/"+SystemInfo.getPackageName(context)+"/"+path);
			}
			else
			{
				f = new File(path);
			}
			if(f!=null&&!f.exists())
			{
				try {
					f.createNewFile();
				} catch (IOException e) {
				}
			}
			if(f!=null&&f.exists())
			{
				filePath = f.getAbsolutePath();
			}
		}
		return filePath;
	}
	
	public static String createSdcardEmptyFile(Context context,String path) {
		String filePath = null;
		if(path!=null&&path.length()>0)
		{
			File f;
			if(path.startsWith("/"))
			{
				f = new File(path);
				if(!f.exists())
				{
					try {
						f.createNewFile();
					} catch (IOException e) {
					}
				}
				if(f!=null&&f.exists())
				{
					filePath = f.getAbsolutePath();
				}
			}
			else
			{
				f = new File(sdcardPath+"/"+path);
				if(!f.exists())
				{
					try {
						f.createNewFile();
					} catch (IOException e) {
					}
				}
				if(f!=null&&f.exists())
				{
					filePath = f.getAbsolutePath();
				}
				else
				{
					if(sdcardDirArr!=null&&sdcardDirArr.length>0)
					{
						for(int i=0;i<sdcardDirArr.length;i++)
						{
							f = new File(sdcardDirArr[i]+"/"+path);
							if(!f.exists())
							{
								try {
									f.createNewFile();
								} catch (IOException e) {
								}
							}
							if(f!=null&&f.exists())
							{
								filePath = f.getAbsolutePath();
								break;
							}
						}
					}
				}
			}
		}
		return filePath;
	}
	
	public static String createEmptyFile(Context context,String path) {
		String filePath = null;
		if(path!=null&&path.length()>0)
		{
			if(path.startsWith("/data/data/"))
			{
				filePath = createPhoneDir(context,path);
			}
			else if(!path.startsWith("/"))
			{
				filePath = createSdcardDir(context,path);
				if(filePath!=null&&filePath.length()>0)
				{
					filePath = createPhoneDir(context,path);
				}
			}
			else
			{
				filePath = createSdcardDir(context,path);
			}
		}
		return filePath;
	}
	
	public static boolean deleteFile(File f) {
		boolean result = false;
		if(f!=null&&f.exists())
		{
			if(f.isDirectory())
			{
				File farr[] = f.listFiles();
				if(farr!=null&&farr.length>0)
				{
					for(int i=0;i<farr.length;i++)
					{
						deleteFile(farr[i]);
					}
				}
			}
			result = f.delete();
		}
		return result;
	}
	
	public boolean deletePhoneFile(Context context,String path) {
		boolean result = false;
		if(path!=null&&path.length()>0)
		{
			File f = null;
			if(path.startsWith("/data/data/"))
			{
				f = new File(path);
			}
			else if(!path.startsWith("/"))
			{
				f = new File("/data/data/"+SystemInfo.getPackageName(context)+"/"+path);
			}
			else
			{
				f = new File(path);
			}
			if(f!=null&&f.exists())
			{
				result = deleteFile(f);
			}
		}
		return result;
	}
	
	public boolean deleteSdcardFile(Context context,String path) {
		boolean result = false;
		if(path!=null&&path.length()>0)
		{
			File f;
			if(path.startsWith("/"))
			{
				f = new File(path);
				if(f!=null&&f.exists())
				{
					result = deleteFile(f);
				}
			}
			else
			{
				f = new File(sdcardPath+"/"+path);
				if(f!=null&&f.exists())
				{
					result = deleteFile(f);
				}
				else
				{
					if(sdcardDirArr!=null&&sdcardDirArr.length>0)
					{
						for(int i=0;i<sdcardDirArr.length;i++)
						{
							f = new File(sdcardDirArr[i]+"/"+path);
							if(f!=null&&f.exists())
							{
								result = deleteFile(f);
								break;
							}
						}
					}
				}
			}
		}
		return result;
	}
	
	public boolean deleteFile(Context context,String path) {
		boolean result = false;
		if(path!=null&&path.length()>0)
		{
			if(path.startsWith("/data/data/"))
			{
				result = deletePhoneFile(context,path);
			}
			else if(!path.startsWith("/"))
			{
				result = deleteSdcardFile(context,path);
				if(!result)
				{
					result = deletePhoneFile(context,path);
				}
			}
			else
			{
				result = deleteSdcardFile(context,path);
			}
		}
		return result;
	}
	
	public boolean movePhoneFileToPhone(Context context,String sourcePath,String newPath,boolean cover) {
		boolean result = false;
		if(sourcePath!=null&&sourcePath.length()>0&&newPath!=null&&newPath.length()>0)
		{
			File sourceFile = null;
			if(sourcePath.startsWith("/data/data/"))
			{
				sourceFile = new File(sourcePath);
			}
			else if(!sourcePath.startsWith("/"))
			{
				sourceFile = new File("/data/data/"+SystemInfo.getPackageName(context)+"/"+sourcePath);
			}
			else
			{
				sourceFile = new File(sourcePath);
			}
			
			File newFile = null;
			if(newPath.startsWith("/data/data/"))
			{
				newFile = new File(newPath);
			}
			else if(!newPath.startsWith("/"))
			{
				newFile = new File("/data/data/"+SystemInfo.getPackageName(context)+"/"+newPath);
			}
			else
			{
				newFile = new File(newPath);
			}
			
			if(sourceFile!=null&&sourceFile.exists())
			{
				if(newFile!=null)
				{
					if(cover)
					{
						if(newFile.exists())
						{
							deleteFile(context,newFile.getAbsolutePath());
						}
					}
					if(sourceFile.isDirectory())
					{
						result = sourceFile.renameTo(newFile);
					}
					else
					{
						result = sourceFile.renameTo(newFile);
					}
				}
			}
			
		}
		return result;
	}
	
	public boolean moveSdcardFileToSdcard(Context context,String sourcePath,String newPath,boolean cover) {
		boolean result = false;
		if(sourcePath!=null&&sourcePath.length()>0&&newPath!=null&&newPath.length()>0)
		{
			String sdcardPath = getSdcardPath(4*1024*1024L);//最少空间为4MB
			File sourceFile = null;
			if(!sourcePath.startsWith("/"))
			{
				sourceFile = new File(sdcardPath+"/"+sourcePath);
			}
			else
			{
				sourceFile = new File(sourcePath);
			}
			
			File newFile = null;
			if(!newPath.startsWith("/"))
			{
				newFile = new File(sdcardPath+"/"+newPath);
			}
			else
			{
				newFile = new File(newPath);
			}
			
			if(sourceFile!=null&&sourceFile.exists())
			{
				if(newFile!=null)
				{
					if(cover)
					{
						if(newFile.exists())
						{
							deleteFile(context,newFile.getAbsolutePath());
						}
					}
					if(sourceFile.isDirectory())
					{
						result = sourceFile.renameTo(newFile);
					}
					else
					{
						result = sourceFile.renameTo(newFile);
					}
				}
			}
			
		}
		return result;
	}
	
	public boolean movePhoneFileToSdcard(Context context,String sourcePath,String newPath,boolean cover) {
		boolean result = false;
		if(sourcePath!=null&&sourcePath.length()>0&&newPath!=null&&newPath.length()>0)
		{
			String sdcardPath = getSdcardPath(4*1024*1024L);//最少空间为4MB
			File sourceFile = null;
			if(sourcePath.startsWith("/data/data/"))
			{
				sourceFile = new File(sourcePath);
			}
			else if(!sourcePath.startsWith("/"))
			{
				sourceFile = new File("/data/data/"+SystemInfo.getPackageName(context)+"/"+sourcePath);
			}
			else
			{
				sourceFile = new File(sourcePath);
			}
			
			File newFile = null;
			if(!newPath.startsWith("/"))
			{
				newFile = new File(sdcardPath+"/"+newPath);
			}
			else
			{
				newFile = new File(newPath);
			}
			
			if(sourceFile!=null&&sourceFile.exists())
			{
				if(newFile!=null)
				{
					if(cover)
					{
						if(newFile.exists())
						{
							deleteFile(context,newFile.getAbsolutePath());
						}
					}
					if(sourceFile.isDirectory())
					{
						result = copyFileToParentFile(context,sourceFile,newFile.getParentFile())&&deleteFile(sourceFile);
					}
					else
					{
						result = copyFileToFile(context,sourceFile,newFile)&&deleteFile(sourceFile);
					}
				}
			}
		}
		return result;
	}
	
	public boolean moveSdcardFileToPhone(Context context,String sourcePath,String newPath,boolean cover) {
		boolean result = false;
		if(sourcePath!=null&&sourcePath.length()>0&&newPath!=null&&newPath.length()>0)
		{
			String sdcardPath = getSdcardPath(4*1024*1024L);//最少空间为4MB
			File sourceFile = null;
			if(!sourcePath.startsWith("/"))
			{
				sourceFile = new File(sdcardPath+"/"+sourcePath);
			}
			else
			{
				sourceFile = new File(sourcePath);
			}
			
			
			File newFile = null;
			if(newPath.startsWith("/data/data/"))
			{
				newFile = new File(newPath);
			}
			else if(!newPath.startsWith("/"))
			{
				newFile = new File("/data/data/"+SystemInfo.getPackageName(context)+"/"+newPath);
			}
			else
			{
				newFile = new File(newPath);
			}
			
			if(sourceFile!=null&&sourceFile.exists())
			{
				if(newFile!=null)
				{
					if(cover)
					{
						if(newFile.exists())
						{
							deleteFile(context,newFile.getAbsolutePath());
						}
					}
					if(sourceFile.isDirectory())
					{
						result = copyFileToParentFile(context,sourceFile,newFile.getParentFile())&&deleteFile(sourceFile);
					}
					else
					{
						result = copyFileToFile(context,sourceFile,newFile)&&deleteFile(sourceFile);
					}
				}
			}
		}
		return result;
	}
	
	public boolean copyFileToFile(Context context,File sourceFile,File newFile) {
		boolean result = false;
		if(sourceFile!=null&&sourceFile.exists())
		{
			if(sourceFile.isFile())
			{
				try {
					InputStream ins = new FileInputStream(sourceFile);
					OutputStream outs = new FileOutputStream(newFile);
					result = inputStreamToOutputStream(ins,outs);
				} catch (FileNotFoundException e) {
				}
			}
			else
			{
				newFile.mkdirs();
				result = true;
				File flist[] = sourceFile.listFiles();
				if(flist!=null&&flist.length>0)
				{
					for(int i=0;i<flist.length;i++)
					{
						if(!copyFileToParentFile(context,flist[i],newFile))
						{
							result = false;
						}
					}
				}
			}
		}
		return result;
	}
	
	public boolean copyFileToParentFile(Context context,File sourceFile,File parentFile) {
		boolean result = false;
		if(sourceFile!=null&&sourceFile.exists())
		{
			if(!parentFile.exists())
			{
				parentFile.mkdirs();
			}
			if(sourceFile.isFile())
			{
				try {
					InputStream ins = new FileInputStream(sourceFile);
					OutputStream outs = new FileOutputStream(new File(parentFile.getAbsolutePath(),sourceFile.getName()));
					result = inputStreamToOutputStream(ins,outs);
				} catch (FileNotFoundException e) {
				}
			}
			else
			{
				File newFile = new File(parentFile.getAbsolutePath(),sourceFile.getName());
				newFile.mkdirs();
				result = true;
				File flist[] = sourceFile.listFiles();
				if(flist!=null&&flist.length>0)
				{
					for(int i=0;i<flist.length;i++)
					{
						if(!copyFileToParentFile(context,flist[i],newFile))
						{
							result = false;
						}
					}
				}
			}
		}
		return result;
	}
	
	/**
	 * 公用判断字符串是否为空
	 * @param str
	 * @return
	 */
	public static boolean isStringNull(String str) {
		if(str!=null && !"".equals(str) &&!"null".equals(str) && !"NULL".equals(str) && str.length()>0)
		{
			return false ;
		}
		return true ;
	}
	
    /**
     * 获取SharedPreferences数据库中的整型值
     * @param context
     * @param dbname
     * @param valuename
     * @param defaultValue
     * @return
     */
    public static int getSaveData(Context context,String dbname,String valuename,int defaultValue) {
        SharedPreferences pre = context.getSharedPreferences(dbname,Context.MODE_PRIVATE);
        return pre.getInt(valuename,defaultValue);
    }
    
    /**
     * 获取SharedPreferences数据库中的整型值
     * @param context
     * @param dbname
     * @param valuename
     * @param defaultValue
     * @return
     */
    public static long getSaveData(Context context,String dbname,String valuename,long defaultValue) {
        SharedPreferences pre = context.getSharedPreferences(dbname,Context.MODE_PRIVATE);
        return pre.getLong(valuename,defaultValue);
    }
    
    /**
     * 获取SharedPreferences数据库中的boolean型值
     * @param context
     * @param dbname
     * @param valuename
     * @param defaultValue
     * @return
     */
    public static boolean getSaveData(Context context,String dbname,String valuename,boolean defaultValue) {
        SharedPreferences pre = context.getSharedPreferences(dbname,Context.MODE_PRIVATE);
        return pre.getBoolean(valuename,defaultValue);
    }
    
    /**
     * 获取SharedPreferences数据库中的字符串值
     * @param context
     * @param dbname
     * @param valuename
     * @param defaultValue
     * @return
     */
    public static String getSaveData(Context context,String dbname,String valuename,String defaultValue) {
        SharedPreferences pre = context.getSharedPreferences(dbname,Context.MODE_PRIVATE);
        return pre.getString(valuename,defaultValue);
    }
    
    /**
     * 保存整型值到SharedPreferences数据库中
     * @param context
     * @param dbname
     * @param valuename
     * @param value
     */
    public static void saveData(Context context,String dbname,String valuename,int value) {
        SharedPreferences pre = context.getSharedPreferences(dbname,Context.MODE_PRIVATE);
        Editor edit = pre.edit();
        edit.putInt(valuename, value);
        edit.commit();
    }
    
    /**
     * 保存整型值到SharedPreferences数据库中
     * @param context
     * @param dbname
     * @param valuename
     * @param value
     */
    public static void saveData(Context context,String dbname,String valuename,long value) {
        SharedPreferences pre = context.getSharedPreferences(dbname,Context.MODE_PRIVATE);
        Editor edit = pre.edit();
        edit.putLong(valuename, value);
        edit.commit();
    }
    
    /**
     * 保存boolean型值到SharedPreferences数据库中
     * @param context
     * @param dbname
     * @param valuename
     * @param value
     */
    public static void saveData(Context context,String dbname,String valuename,boolean value) {
        SharedPreferences pre = context.getSharedPreferences(dbname,Context.MODE_PRIVATE);
        Editor edit = pre.edit();
        edit.putBoolean(valuename, value);
        edit.commit();
    }
    
    /**
     * 保存字符串值到SharedPreferences数据库中
     * @param context
     * @param dbname
     * @param valuename
     * @param value
     */
    public static void saveData(Context context,String dbname,String valuename,String value) {
        SharedPreferences pre = context.getSharedPreferences(dbname,Context.MODE_PRIVATE);
        Editor edit = pre.edit();
        edit.putString(valuename, value);
        edit.commit();
    }
    
	/**
	 * 根据分隔符获取字符串列表
	 * @param source
	 * @param split
	 * @return
	 */
	public static ArrayList<String> splitStr(String source,String split) {
		if(source==null||source.length()==0||split==null||split.length()==0)
		{
			return null;
		}
		ArrayList<String> list = new ArrayList<String>();
		int index = source.indexOf(split);
		while(index>=0)
		{
			if(index==0)
			{
				list.add("");
			}
			else
			{
				list.add(source.substring(0, index));
			}
			source = source.substring(index+1);
			index = source.indexOf(split);
		}
		list.add(source);
		return list;
	}
	
	/**
	 * 合并字符串列表为字符串
	 * @param list
	 * @param split
	 * @return
	 */
	public static String mergeStr(ArrayList<String> list,String split) {
		if(list==null||list.size()==0||split==null||split.length()==0)
		{
			return null;
		}
		String str="";
		for(int i=0;i<list.size();i++) {
			str+=list.get(i);
			if(i<list.size()-1)
			{
				str+=split;
			}
		}
		return str;
	}
	
	/**
	 * 链表转数组
	 * @param list
	 * @return
	 */
	public static String[] arrayListToArr(ArrayList<String> list) {
		String[] arr=null;
		if(list!=null)
		{
			arr = new String[list.size()];
			for(int i=0;i<list.size();i++) {
				arr[i]=list.get(i);
			}
		}
		return arr;
	}
	
	/**
	 * 打开网络设置
	 * @param context
	 */
	public static void openNetWorkSettings(Context context) {
		String action = android.provider.Settings.ACTION_SETTINGS;
		if(android.os.Build.VERSION.SDK_INT <= 10 ){
			action = android.provider.Settings.ACTION_WIRELESS_SETTINGS;
		}
		Intent intent = new Intent(action);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS|Intent.FLAG_ACTIVITY_CLEAR_TOP);
		try {
			context.startActivity(intent);
		} catch(Exception e) {
			openSettings(context);
		}
	}
	
	/**
	 * 打开语音合成设置
	 * @param context
	 */
	public static void openTextToSpeechSettings(Context context) {//"com.android.settings.Settings"  "com.android.settings.LanguageSettings" "com.android.settings.Settings$TextToSpeechSettingsActivity"
		Intent intent = new Intent(Intent.ACTION_VIEW);//Intent.ACTION_VIEW "com.android.settings.VoiceInputOutputSettings"
		intent.setClassName("com.android.settings", "com.android.settings.TextToSpeechSettings");//"com.android.settings.TextToSpeechSettings"//TextToSpeechSettingsActivity
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS|Intent.FLAG_ACTIVITY_CLEAR_TOP);
		try {
			context.startActivity(intent);
		} catch(Exception e) {
			openLanguageSettings(context);
		}
	}
	
	public static void openLanguageSettings(Context context) {//"com.android.settings.Settings"  "com.android.settings.LanguageSettings" "com.android.settings.Settings$TextToSpeechSettingsActivity"
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setClassName("com.android.settings", "com.android.settings.LanguageSettings");
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS|Intent.FLAG_ACTIVITY_CLEAR_TOP);
		try {
			context.startActivity(intent);
		} catch(Exception e) {
			openSettings(context);
		}
	}
	
	public static void openSettings(Context context) {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setClassName("com.android.settings", "com.android.settings.Settings");
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS|Intent.FLAG_ACTIVITY_CLEAR_TOP);
		try {
			context.startActivity(intent);
		} catch(Exception e) {
		}
	}
	
	/**
	 * 正则表达式匹配
	 * @param source
	 * @param regex
	 * @return
	 */
	public static Matcher getMatcher(String source,String regex) {
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(source);
		return matcher;
	}
	
	/**
	 * 返回正则表达式匹配的结果
	 * @param source
	 * @param regex
	 * @return
	 */
	public static boolean matcher(String source,String regex) {
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(source);
		return matcher.matches();
	}
	
	/**
	 * 返回正则表达式匹配到的对应字符串
	 * @param source
	 * @param regex
	 * @param index
	 * @return
	 */
	public static String getMatcherGroup(String source,String regex,int index) {
		String result = null;
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(source);
		if(matcher.find()) {
			if(index<=matcher.groupCount())
			{
				try {
					result = matcher.group(index);
				} catch(IndexOutOfBoundsException e) {
					
				} catch(IllegalStateException e) {
					
				}
			}
		}
		return result;
	}
    
    /**
     * 读取文本文件
     * @param path
     * @return
     */
	public static String readFile(String path) {
		if(path!=null&&path.length()>0)
		{
			try {
				InputStream in = new FileInputStream(path);
				if(in!=null&&in.available()>0)
				{
					BufferedReader reader=new BufferedReader(new InputStreamReader(in,"UTF-8"));
					String line=null;
					StringBuilder sb=new StringBuilder();
					while((line=reader.readLine())!=null)
					{
						sb.append(line);
					}
					return sb.toString();
				}
			} catch (FileNotFoundException e) {
			} catch (ParseException e) {
			} catch (IOException e) {
			}
		}
		return null;
	}
	
	/**
     * 读取文本文件
     * @param path
     * @return
     */
	public static String readAssetsFile(Context context,String name) {
		if(name!=null&&name.length()>0)
		{
			try {
				InputStream in = context.getResources().getAssets().open(name);
				if(in!=null&&in.available()>0)
				{
					BufferedReader reader=new BufferedReader(new InputStreamReader(in,"UTF-8"));
					String line=null;
					StringBuilder sb=new StringBuilder();
					while((line=reader.readLine())!=null)
					{
						sb.append(line);
					}
					return sb.toString();
				}
			} catch (FileNotFoundException e) {
			} catch (ParseException e) {
			} catch (IOException e) {
			}
		}
		return null;
	}
	
	/**
	 * 检测是否存在Assets文件
	 * @param context
	 * @param name
	 * @return
	 */
	public static boolean isAssetsFileExists(Context context,String name) {
		boolean result = false;
		if(name!=null&&name.length()>0)
		{
			try {
				InputStream in = context.getResources().getAssets().open(name);
				if(in!=null&&in.available()>0)
				{
					result = true;
				}
			} catch (FileNotFoundException e) {
			} catch (ParseException e) {
			} catch (IOException e) {
			}
		}
		return result;
	}
	
	/**
	 * 字符串格式化处理
	 * @param speak
	 * @return
	 */
	public static String FormatSpeakString(String speak) {
		if(speak!=null&&speak.length()>0)
		{
			String []replace = {",","，",".","。","!","！","?","？",":","：","'","‘","’","\"","“","”",";","；"};
			speak = speak.trim();
			String str;
			for(int i=0;i<replace.length;i++) {
				str = replace[i];
				speak = speak.replace(str, "");
			}
		}
		return speak;
	}
	
    /**
     * 检测当前应用是否具有某项权限
     * @param context
     * @param permission
     * @param packageName
     * @return
     */
    public static boolean checkCurrentAppPermission(Context context,String permission) {
    	 boolean reslut = false;
    	 try {
    		 int resultCode = context.checkCallingOrSelfPermission(permission);
    		 if(resultCode == PackageManager.PERMISSION_GRANTED){
    			 reslut = true;
    			 showLog("muge", "CurrentApp has Permission:"+permission);
    		 }
    		 else
    		 {
    			 showLog("muge", "CurrentApp has not Permission:"+permission);
    		 }
    	 } catch(NullPointerException e) {
    		 
    	 } catch(Exception e) {
    		 
    	 }
    	 return reslut;
    }
    
    /**
     * 数据拷贝基本方法，从InputStream拷贝到OutputStream，每次拷贝大小不超过10K
     * @param ins
     * @param outs
     * @return
     */
    private static boolean inputStreamToOutputStream(InputStream ins,OutputStream outs) {
    	if(ins!=null&&outs!=null)
    	{
    		try {
				int total = ins.available();
				if(total>0)
				{
					showLog("ZSZ-Tools", "inputStreamToOutputStream() total="+total);
					int k = 10*1024;//每次拷贝10K
					byte []b = null;
					if(total>k)
					{
						b = new byte[k];
					}
					else
					{
						b = new byte[total];
					}
					int temp;
					while(total>0)
					{
						temp = ins.read(b);
						outs.write(b,0,temp);
						outs.flush();
						total-=temp;
						showLog("ZSZ-Tools", "inputStreamToOutputStream() remain="+total);
					}
					outs.close();
					outs = null;
					ins.close();
					ins = null;
					return true;
				}
				outs.close();
				outs = null;
				ins.close();
				ins = null;
    	    } catch (IOException e) {
    	    	showLog("ZSZ-Tools", "inputStreamToOutputStream() IOException:"+e.getMessage());
    		} catch (IndexOutOfBoundsException e) {
    	    	showLog("ZSZ-Tools", "inputStreamToOutputStream() IndexOutOfBoundsException:"+e.getMessage());
    		}
    	}
    	return false;
    }
    
    /**
     * 拷贝Assets里面的文件到手机私有files目录下
     * @param context
     * @param fromFileName
     * @param toFileName
     * @return
     */
    public static boolean copyAssetFileToPhone(Context context,String fromFileName,String toFileName) {
    	showLog("ZSZ-Tools", "copyAssetFileToPhone() fromFileName="+fromFileName+" toFileName="+toFileName);
    	if(context!=null&&fromFileName!=null&&toFileName!=null)
    	{
	    	try {
				InputStream ins = context.getAssets().open(fromFileName);
				File f = context.getFileStreamPath(toFileName);
				File ftemp = context.getFileStreamPath(toFileName+".temp");
				if(ins!=null)
				{
					int total = ins.available();
					if(total>0)
					{
						if(f.exists()&&total==f.length())
						{
							return true;
						}
					}
					else
					{
						return false;
					}
				}
				else
				{
					return false;
				}
				f.delete();
				ftemp.delete();
				FileOutputStream outs = context.openFileOutput(toFileName+".temp",Context.MODE_WORLD_READABLE|Context.MODE_WORLD_WRITEABLE);
				return inputStreamToOutputStream(ins,outs)&&ftemp.renameTo(f);
		    } catch (FileNotFoundException e) {
		    	showLog("ZSZ-Tools", "copyAssetFileToPhone() FileNotFoundException:"+e.getMessage());
		    } catch (IOException e) {
	    		showLog("ZSZ-Tools", "copyAssetFileToPhone() IOException:"+e.getMessage());
			}
    	}
    	return false;
    }
    
    /**
     * 获取ZZ安装功能的ComponentName
     * @param context
     * @return
     */
    public static Intent getWakeUpPackageIntent(Context context,String packageName) {
    	Intent intent = null;
    	if(context!=null&&packageName!=null&&packageName.length()>0)
		{
    		ApplicationInfo info = getApplicationInfo(context,packageName,PackageManager.GET_META_DATA);
    		Bundle metaData;
    		String zzWakeupAction;
    		String zzWakeupReceiver;
    		if(info!=null)
    		{
    			metaData = info.metaData;
    			if(metaData!=null)
    			{
    				zzWakeupAction = metaData.getString("zzWakeupAction");
    				zzWakeupReceiver = metaData.getString("zzWakeupReceiver");
            		if(zzWakeupAction!=null&&zzWakeupAction.length()>0&&zzWakeupReceiver!=null&&zzWakeupReceiver.length()>0)
            		{
            			intent = new Intent(zzWakeupAction);
            			intent.setClassName(packageName, zzWakeupReceiver);
            		}
    			}
    		}
		}
    	return intent;
    }
	
    public static void unZip(String zipFile, String zipBasePath,String fileName ,String savePath) {
    	showLog("CmdManager", "unZip() fileName="+fileName+" savePath="+savePath);
		int BUFFER = 4096; //这里缓冲区我们使用4KB，
		String strEntry; //保存每个zip的条目名称
		try {
			BufferedOutputStream dest = null; //缓冲输出流
			FileInputStream fis = new FileInputStream(zipFile);
			ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
			ZipEntry entry; //每个zip条目的实例
			byte data[] = null;
			while ((entry = zis.getNextEntry()) != null) {
				try {
					showLog("Unzip： ","="+ entry);
					int count;
					strEntry = entry.getName();
					showLog("CmdManager", "unZip() entry.getName()="+entry.getName());
					if(strEntry!=null&&strEntry.startsWith(zipBasePath)&&strEntry.endsWith(fileName))
					{
						showLog("CmdManager", "unZip() strEntry!=null&&strEntry.equals(fileName)");
						data = new byte[BUFFER];
						File entryFile = new File(savePath,fileName);
						File entryDir = new File(savePath);
						showLog("Unzip", "entryFilename="+entryFile.getName()+" entryFilepath="+entryFile.getAbsolutePath());
						if (!entryDir.exists()) {
							entryDir.mkdirs();
							showLog("Unzip", "dirname="+entryDir.getName()+" dirpath="+entryDir.getAbsolutePath());
						}
						FileOutputStream fos = new FileOutputStream(entryFile);
						dest = new BufferedOutputStream(fos, BUFFER);
						while ((count = zis.read(data, 0, BUFFER))!= -1) {
							showLog("Unzip", "count="+count);
							dest.write(data, 0, count);
						}
						dest.flush();
						dest.close();
						break;
					}
				} catch (Exception ex) {
					showLog("CmdManager", "unZip() try Exception="+ex.getMessage());
				}
			}
			zis.close();
		} catch (Exception e) {
			showLog("CmdManager", "unZip() big try Exception="+e.getMessage());
		}
	}
    
    /**
     * 发送来电播报配置信息发生更新的广播
     * @param context
     * @param packageName
     */
    public static void sendSpeechSettingUpdateBroadcast(Context context,String packageName) {
		Intent intent = new Intent("com.zzcm.yyassistant.client.home.SpeechSettingUpdate");
		if(context!=null)
		{
			if(packageName!=null)
			{
				intent.putExtra("fromPackageName", packageName);
			}
			context.sendBroadcast(intent);
		}
	}
	
	public static JSONObject parserJSONObject(String jsonObjStr) {
		JSONObject obj  = null;
		try {
			obj = new JSONObject(jsonObjStr);
		} catch(JSONException e) {
			showLog("muge", "JSON协议解析异常！jsonObjStr="+jsonObjStr);
		} catch(Exception e) {
			showLog("muge", "Exception :"+e.getMessage());
		}
		return obj;
	}
	
	public static JSONArray parserJSONArray(String jsonArrStr) {
		JSONArray obj  = null;
		try {
			obj = new JSONArray(jsonArrStr);
		} catch(JSONException e) {
			showLog("muge", "JSON协议解析异常！jsonArrStr="+jsonArrStr);
		} catch(Exception e) {
			showLog("muge", "Exception :"+e.getMessage());
		}
		return obj;
	}
	
	public static String getUniqueString(String url) {
    	if(url!=null)
    	{
    		int len = url.length();
    		if(len>0)
    		{
    			String urlChange = url.substring((len-1)/4+1, (len-1)/2+1)+url.substring(3*(len-1)/4+1, len)+url.substring(0, (len-1)/4+1)+url.substring((len-1)/2+1, 3*(len-1)/4+1);
    			url = len+"-"+url.hashCode()+"-"+urlChange.hashCode();
    		}
    	}
    	return url;
    }
	
	public static void call(Context context,String number) {
		if(number!=null&&number.length()>0)
		{
			Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+number));
			try {
				context.startActivity(intent);
			} catch(ActivityNotFoundException e) {
				
			} catch(Exception e) {
				
			}
		}
	}
	
    
    /**
     * 通过包名打开文件
     * @return
     */
    public static boolean openApp(Context context, String packageName) {
        try {
            PackageManager packageManager = context.getPackageManager();
            Intent intent = packageManager.getLaunchIntentForPackage(packageName);
            if(intent!=null)
            {
	            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
	                    | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
	            if(context!=null)
	            {
	            	context.startActivity(intent);
	            	Tools.showLog("InstallAppHelper", "openApp() packageName="+packageName+" sucess");
	            	return true;
	            }
            }
        } catch (Exception e) {
        }
        Tools.showLog("InstallAppHelper", "openApp() packageName="+packageName+" fail");
        return false;
    }
    
    public static Intent createIntent(Context context,String jsonData) {
    	Intent intent = null;
    	if(jsonData!=null&&jsonData.length()>0)
    	{
    		JSONObject jsonObj = Tools.parserJSONObject(jsonData);
    		if(jsonObj!=null)
        	{
    			intent = createIntent(context,jsonObj);
        	}
    	}
    	return intent;
    }
    
    public static Intent createIntent(Context context,JSONObject jsonObj) {
    	Intent intent = null;
    	if(jsonObj!=null)
    	{
    		intent = new Intent();
    		String action = jsonObj.optString("action");
    		if(action!=null&&action.length()>0)
    		{
    			intent.setAction(action);
    		}
    		String category = jsonObj.optString("category");
    		if(category!=null&&category.length()>0)
    		{
    			intent.addCategory(category);
    		}
			JSONArray jsonArr = jsonObj.optJSONArray("flags");
			if(jsonArr!=null&&jsonArr.length()>0)
			{
				for(int i=0;i<jsonArr.length();i++) {
					intent.addFlags(jsonArr.optInt(i));
				}
			}
    		String data = jsonObj.optString("data");
    		if(data!=null&&data.length()>0)
    		{
    			intent.setData(Uri.parse(data));
    		}
    		String type = jsonObj.optString("type");
    		if(type!=null&&type.length()>0)
    		{
    			intent.setType(type);
    		}
    		String packageName = jsonObj.optString("packageName");
    		String className = jsonObj.optString("className");
    		if(packageName!=null&&packageName.length()>0)
    		{
    			if(className!=null&&className.length()>0)
    			{
    				intent.setClassName(packageName, className);
    			}
    			else
    			{
    				intent.setPackage(packageName);
    			}
    		}
    		else if(className!=null&&className.length()>0)
			{
    			intent.setClassName(context, className);
    		}
    		JSONArray extra = jsonObj.optJSONArray("extra");
    		if(extra!=null&&extra.length()>0)
    		{
    			JSONObject extraObj;
    			for(int i=0;i<extra.length();i++) {
    				extraObj = extra.optJSONObject(i);
    				if(extraObj!=null)
    				{
    					String name = extraObj.optString("name");
    					if(name!=null&&name.length()>0)
    					{
    						String valueType = extraObj.optString("valueType");
    						if(valueType==null||valueType.length()==0)
    						{
    							valueType = "String";
    						}
    						if(valueType.equalsIgnoreCase("boolean"))
    						{
    							intent.putExtra(name, extraObj.optBoolean("value"));
    						}
    						else if(valueType.equalsIgnoreCase("boolean[]"))
    						{
    							JSONArray booleanArr = extraObj.optJSONArray("value");
    							if(booleanArr!=null)
    							{
    								intent.putExtra(name,getBooleanArrayFromJSONArray(booleanArr));
    							}
    						}
    						else if(valueType.equalsIgnoreCase("byte"))
    						{
    							intent.putExtra(name, (byte)extraObj.optInt("value"));
    						}
    						else if(valueType.equalsIgnoreCase("byte[]"))
    						{
    							JSONArray byteArr = extraObj.optJSONArray("value");
    							if(byteArr!=null)
    							{
    								intent.putExtra(name,getByteArrayFromJSONArray(byteArr));
    							}
    						}
    						else if(valueType.equalsIgnoreCase("char"))
    						{
    							String temp = extraObj.optString("value");
    							if(temp!=null&&temp.length()>0)
    							{
    								intent.putExtra(name, temp.charAt(0));
    							}
    						}
    						else if(valueType.equalsIgnoreCase("char[]"))
    						{
    							JSONArray charArr = extraObj.optJSONArray("value");
    							if(charArr!=null)
    							{
    								intent.putExtra(name,getCharArrayFromJSONArray(charArr));
    							}
    						}
    						else if(valueType.equalsIgnoreCase("int"))
    						{
    							intent.putExtra(name, extraObj.optInt("value"));
    						}
    						else if(valueType.equalsIgnoreCase("int[]"))
    						{
    							JSONArray intArr = extraObj.optJSONArray("value");
    							if(intArr!=null)
    							{
    								intent.putExtra(name,getIntArrayFromJSONArray(intArr));
    							}
    						}
    						else if(valueType.equalsIgnoreCase("short"))
    						{
    							intent.putExtra(name, (short)extraObj.optInt("value"));
    						}
    						else if(valueType.equalsIgnoreCase("short[]"))
    						{
    							JSONArray shortArr = extraObj.optJSONArray("value");
    							if(shortArr!=null)
    							{
    								intent.putExtra(name,getShortArrayFromJSONArray(shortArr));
    							}
    						}
    						else if(valueType.equalsIgnoreCase("long"))
    						{
    							intent.putExtra(name, extraObj.optLong("value"));
    						}
    						else if(valueType.equalsIgnoreCase("long[]"))
    						{
    							JSONArray longArr = extraObj.optJSONArray("value");
    							if(longArr!=null)
    							{
    								intent.putExtra(name,getLongArrayFromJSONArray(longArr));
    							}
    						}
    						else if(valueType.equalsIgnoreCase("float"))
    						{
    							String temp = extraObj.optString("value");
    							if(temp!=null&&temp.length()>0)
    							{
    								intent.putExtra(name, Float.parseFloat(temp));
    							}
    						}
    						else if(valueType.equalsIgnoreCase("float[]"))
    						{
    							JSONArray floatArr = extraObj.optJSONArray("value");
    							if(floatArr!=null)
    							{
    								intent.putExtra(name,getFloatArrayFromJSONArray(floatArr));
    							}
    						}
    						else if(valueType.equalsIgnoreCase("double"))
    						{
    							String temp = extraObj.optString("value");
    							if(temp!=null&&temp.length()>0)
    							{
    								intent.putExtra(name, Double.parseDouble(temp));
    							}
    						}
    						else if(valueType.equalsIgnoreCase("double[]"))
    						{
    							JSONArray doubleArr = extraObj.optJSONArray("value");
    							if(doubleArr!=null)
    							{
    								intent.putExtra(name,getDoubleArrayFromJSONArray(doubleArr));
    							}
    						}
    						else if(valueType.equalsIgnoreCase("CharSequence"))
    						{
    							String temp = extraObj.optString("value");
    							if(temp!=null)
    							{
    								intent.putExtra(name, (CharSequence)temp);
    							}
    						}
    						else if(valueType.equalsIgnoreCase("CharSequence[]"))
    						{
    							JSONArray charSequenceArr = extraObj.optJSONArray("value");
    							if(charSequenceArr!=null)
    							{
    								intent.putExtra(name,getCharSequenceArrayFromJSONArray(charSequenceArr));
    							}
    						}
    						else if(valueType.equalsIgnoreCase("String"))
    						{
    							String temp = extraObj.optString("value");
    							if(temp!=null)
    							{
    								intent.putExtra(name, temp);
    							}
    						}
    						else if(valueType.equalsIgnoreCase("String[]"))
    						{
    							JSONArray stringArr = extraObj.optJSONArray("value");
    							if(stringArr!=null)
    							{
    								intent.putExtra(name,getStringArrayFromJSONArray(stringArr));
    							}
    						}
    						else if(valueType.equalsIgnoreCase("ArrayList<CharSequence>"))
    						{
    							JSONArray charSequenceArrayList = extraObj.optJSONArray("value");
    							if(charSequenceArrayList!=null)
    							{
    								intent.putCharSequenceArrayListExtra(name, getCharSequenceArrayListFromJSONArray(charSequenceArrayList));
    							}
    						}
    						else if(valueType.equalsIgnoreCase("ArrayList<Integer>"))
    						{
    							JSONArray integerArrayList = extraObj.optJSONArray("value");
    							if(integerArrayList!=null)
    							{
    								intent.putIntegerArrayListExtra(name, getIntegerArrayListFromJSONArray(integerArrayList));
    							}
    						}
    						else if(valueType.equalsIgnoreCase("ArrayList<String>"))
    						{
    							JSONArray stringArrayList = extraObj.optJSONArray("value");
    							if(stringArrayList!=null)
    							{
    								intent.putStringArrayListExtra(name, getStringArrayListFromJSONArray(stringArrayList));
    							}
    						}
    					}
    				}
    			}
    		}
    	}
    	return intent;
    }
    
    public static boolean[] getBooleanArrayFromJSONArray(JSONArray jsonArr) {
    	boolean[] result = null;
    	if(jsonArr!=null&&jsonArr.length()>0)
    	{
    		result = new boolean[jsonArr.length()];
    		for(int i=0;i<jsonArr.length();i++) {
    			result[i]=jsonArr.optBoolean(i);
    		}
    	}
    	return result;
    }
    
    public static byte[] getByteArrayFromJSONArray(JSONArray jsonArr) {
    	byte[] result = null;
    	if(jsonArr!=null&&jsonArr.length()>0)
    	{
    		result = new byte[jsonArr.length()];
    		for(int i=0;i<jsonArr.length();i++) {
    			result[i]=(byte)jsonArr.optInt(i);
    		}
    	}
    	return result;
    }
    
    public static int[] getIntArrayFromJSONArray(JSONArray jsonArr) {
    	int[] result = null;
    	if(jsonArr!=null&&jsonArr.length()>0)
    	{
    		result = new int[jsonArr.length()];
    		for(int i=0;i<jsonArr.length();i++) {
    			result[i]=jsonArr.optInt(i);
    		}
    	}
    	return result;
    }
    
    public static short[] getShortArrayFromJSONArray(JSONArray jsonArr) {
    	short[] result = null;
    	if(jsonArr!=null&&jsonArr.length()>0)
    	{
    		result = new short[jsonArr.length()];
    		for(int i=0;i<jsonArr.length();i++) {
    			result[i]=(short)jsonArr.optInt(i);
    		}
    	}
    	return result;
    }
    
    public static long[] getLongArrayFromJSONArray(JSONArray jsonArr) {
    	long[] result = null;
    	if(jsonArr!=null&&jsonArr.length()>0)
    	{
    		result = new long[jsonArr.length()];
    		for(int i=0;i<jsonArr.length();i++) {
    			result[i]=jsonArr.optLong(i);
    		}
    	}
    	return result;
    }
    
    public static char[] getCharArrayFromJSONArray(JSONArray jsonArr) {
    	char[] result = null;
    	if(jsonArr!=null&&jsonArr.length()>0)
    	{
    		result = new char[jsonArr.length()];
    		String temp;
    		for(int i=0;i<jsonArr.length();i++) {
    			temp = jsonArr.optString(i);
    			if(temp!=null&&temp.length()>0)
    			{
    				result[i]=temp.charAt(0);
    			}
    			else
    			{
    				result[i]=0;
    			}
    		}
    	}
    	return result;
    }
    
    public static float[] getFloatArrayFromJSONArray(JSONArray jsonArr) {
    	float[] result = null;
    	if(jsonArr!=null&&jsonArr.length()>0)
    	{
    		result = new float[jsonArr.length()];
    		String temp;
    		for(int i=0;i<jsonArr.length();i++) {
    			temp = jsonArr.optString(i);
    			if(temp!=null&&temp.length()>0)
    			{
    				result[i]=Float.parseFloat(temp);
    			}
    		}
    	}
    	return result;
    }
    
    public static double[] getDoubleArrayFromJSONArray(JSONArray jsonArr) {
    	double[] result = null;
    	if(jsonArr!=null&&jsonArr.length()>0)
    	{
    		result = new double[jsonArr.length()];
    		String temp;
    		for(int i=0;i<jsonArr.length();i++) {
    			temp = jsonArr.optString(i);
    			if(temp!=null&&temp.length()>0)
    			{
    				result[i]=Double.parseDouble(temp);
    			}
    		}
    	}
    	return result;
    }
    
    public static CharSequence[] getCharSequenceArrayFromJSONArray(JSONArray jsonArr) {
    	CharSequence[] result = null;
    	if(jsonArr!=null&&jsonArr.length()>0)
    	{
    		result = new CharSequence[jsonArr.length()];
    		String temp;
    		for(int i=0;i<jsonArr.length();i++) {
    			temp = jsonArr.optString(i);
    			if(temp!=null)
    			{
    				result[i]=(CharSequence)temp;
    			}
    		}
    	}
    	return result;
    }
    
    public static ArrayList<CharSequence> getCharSequenceArrayListFromJSONArray(JSONArray jsonArr) {
    	ArrayList<CharSequence> result = null;
    	if(jsonArr!=null&&jsonArr.length()>0)
    	{
    		result = new ArrayList<CharSequence>();
    		String temp;
    		for(int i=0;i<jsonArr.length();i++) {
    			temp = jsonArr.optString(i);
    			if(temp!=null)
    			{
    				result.add((CharSequence)temp);
    			}
    		}
    	}
    	return result;
    }
    
    public static ArrayList<Integer> getIntegerArrayListFromJSONArray(JSONArray jsonArr) {
    	ArrayList<Integer> result = null;
    	if(jsonArr!=null&&jsonArr.length()>0)
    	{
    		result = new ArrayList<Integer>();
    		for(int i=0;i<jsonArr.length();i++) {
    			result.add(jsonArr.optInt(i));
    		}
    	}
    	return result;
    }
    
    public static String[] getStringArrayFromJSONArray(JSONArray jsonArr) {
    	String[] result = null;
    	if(jsonArr!=null&&jsonArr.length()>0)
    	{
    		result = new String[jsonArr.length()];
    		for(int i=0;i<jsonArr.length();i++) {
    			result[i] = jsonArr.optString(i);
    		}
    	}
    	return result;
    }
    
    public static ArrayList<String> getStringArrayListFromJSONArray(JSONArray jsonArr) {
    	ArrayList<String> result = null;
    	if(jsonArr!=null&&jsonArr.length()>0)
    	{
    		result = new ArrayList<String>();
    		for(int i=0;i<jsonArr.length();i++) {
    			result.add(jsonArr.optString(i));
    		}
    	}
    	return result;
    }
    
    public static boolean startActivity(Context context,JSONObject jsonObj) {
    	boolean result = false;
    	if(jsonObj!=null)
    	{
    		Intent intent = createIntent(context,jsonObj);
    		try {
    			context.startActivity(intent);
    			result = true;
    		} catch(ActivityNotFoundException e) {
				
			} catch(Exception e) {
				
			}
    	}
    	return result;
    }
    
    public static boolean startActivity(Context context,String jsonData) {
    	JSONObject jsonObj = Tools.parserJSONObject(jsonData);
    	return startActivity(context,jsonObj);
    }
    
    public static boolean startService(Context context,JSONObject jsonObj) {
    	boolean result = false;
    	if(jsonObj!=null)
    	{
    		Intent intent = createIntent(context,jsonObj);
    		try {
    			context.startService(intent);
    			result = true;
    		} catch(SecurityException e) {
				
			} catch(Exception e) {
				
			}
    	}
    	return result;
    }
    
    public static boolean startService(Context context,String jsonData) {
    	JSONObject jsonObj = Tools.parserJSONObject(jsonData);
    	return startService(context,jsonObj);
    }
    
    public static boolean sendBroadcast(Context context,JSONObject jsonObj) {
    	boolean result = false;
    	if(jsonObj!=null)
    	{
    		Intent intent = createIntent(context,jsonObj);
    		try {
    			context.sendBroadcast(intent);
    			result = true;
    		} catch(SecurityException e) {
				
			} catch(Exception e) {
				
			}
    	}
    	return result;
    }
    
    public static boolean sendBroadcast(Context context,String jsonData) {
    	JSONObject jsonObj = Tools.parserJSONObject(jsonData);
    	return sendBroadcast(context,jsonObj);
    }
    
    public static long getFileSize(String path) {
    	long size = -1;
    	if(path!=null&&path.length()>0)
    	{
    		size = new File(path).length();
    	}
    	return size;
    }
    
    public static String getFileMD5(String path) {
    	String md5 = null;
    	if(path!=null&&path.length()>0)
    	{
    		File f = new File(path);
    		if(f.exists())
    		{
    			md5 = getFileMD5(f);
    		}
    	}
    	return md5;
    }
    
    private static char[] hexChar = {
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
    };
    
    private static String toHexString(byte[] b) {
        StringBuilder sb = new StringBuilder(b.length * 2);
        for (int i = 0; i < b.length; i++) {
            sb.append(hexChar[(b[i] & 0xf0) >>> 4]);
            sb.append(hexChar[b[i] & 0x0f]);
        }
        return sb.toString();
    }
    
    /**
     * 获取文件的MD5值
     * @param filePath
     * @return
     */
    public static String getFileMD5(File f) {
        try {
            InputStream fis = new FileInputStream(f);
            byte[] buffer = new byte[1024];
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            int numRead = 0;
            while ((numRead = fis.read(buffer)) > 0) {
                md5.update(buffer, 0, numRead);
            }
            fis.close();
            return toHexString(md5.digest());
        } catch (Exception e) {
        }
        return null;
    }
    
}
